package com.loie.xcx.web.controller;

import com.alibaba.fastjson2.JSONObject;
import com.loie.xcx.comm.JsonResult;
import com.loie.xcx.config.EmailConfig;
import com.loie.xcx.model.bo.EmailBO;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import java.util.Date;
import java.util.Properties;

/**
 * @author zhl
 */
@Slf4j
@RequestMapping("/msg")
@RestController
@AllArgsConstructor
public class MessageController {

    private EmailConfig emailConfig;

    @PostMapping("/sendEmail")
    public JsonResult<EmailBO> sendEmail(@RequestBody String jsonStr) {

        EmailBO emailBO = JSONObject.parseObject(jsonStr, EmailBO.class);
        String emailNo;
        String content;
        String subject;
        if (emailBO != null) {
            emailNo = emailBO.getEmailNo();
            content = emailBO.getContent();
            subject = emailBO.getSubject();
            //处理批量的情况,多邮箱会用;分隔
            String[] arr = emailNo.split(";");
            int receiverCount = arr.length;
            if (StringUtils.isNotBlank(emailNo) && StringUtils.isNotBlank(content) && receiverCount > 0) {
                try {
                    // smtp端口
                    int port = Integer.parseInt(emailConfig.getPort());
                    // smtp服务器地址
                    String server = emailConfig.getUrl().trim();
                    // 发送者
                    String from = emailConfig.getFrom().trim();
                    String user = emailConfig.getUser().trim();
                    // 密码
                    String password = emailConfig.getPassword().trim();
                    Properties props = new Properties();
                    props.put("mail.smtp.host", server);
                    props.put("mail.smtp.port", port);
                    props.put("mail.smtp.auth", "true");
                    MailSSLSocketFactory sf = new MailSSLSocketFactory();
                    sf.setTrustAllHosts(true);
                    props.put("mail.smtp.ssl.enable", "true");
                    props.put("mail.smtp.ssl.socketFactory", sf);

                    Session session = Session.getDefaultInstance(props, null);
                    Transport transport = session.getTransport("smtp");
                    transport.connect(server, user, password);

                    InternetAddress[] address = new InternetAddress[receiverCount];
                    for (int i = 0; i < receiverCount; i++) {
                        address[i] = new InternetAddress(arr[i]);
                    }
                    MimeMessage msg = new MimeMessage(session);
                    msg.setSentDate(new Date());
                    msg.setFrom(new InternetAddress(from));
                    msg.setRecipients(Message.RecipientType.TO, address);
                    msg.setSubject(subject, "UTF-8");
                    msg.setSentDate(new Date());
                    msg.setContent(this.getHtml(content), "text/html;charset=utf-8");
                    transport.sendMessage(msg, msg.getAllRecipients());
                    transport.close();
                    return new JsonResult<>();
                } catch (Exception e) {
                    log.error("EmailChannel.sendEmail===>邮件发送异常！", e);
                }
            }
        }
        return new JsonResult<>(400, "发送失败");
    }

    private String getHtml(String msg) {
        String content = "<!doctype html> " + "<html> " + "<head> " + "<meta charset=\"gb2312\">" + " <title></title> " + "</head> " + " <div class=\"link\" style=' float:right; height:30px; padding:50px 0 3px 0;font-family:\"Microsoft Yahei\";'> "
                + " </div> " + "<div id=\"center\" style=' margin:0 auto; width:650px; background:#f1f1f1; padding:24px 0 0 0 ; '>  ";
        content = content + "<div style=\" width:563px;  margin:0 auto 0 auto; padding:15px 20px; line-height:40px; font-size:14px; background:#00EE76; color:#000000; \">"
                + "<span style=\"font-size:24px; font-weight:bold;\">" + msg + "</span>" +
                "<br/><hr color=\"gray\"/><span style=\"font-size:16px;\">请登录系统查看详情，本邮件由系统自动发出，请勿直接回复！</span>";
        content = content + "</div> ";
        content = content + "<div class='clear'>" + "</div> " + "<div id='foot' style='margin:0 auto; width:610px; font-size:12px; color:#333333; line-height:30px; padding:15px 20px; background:#f1f1f1;'></div></body></html>";
        return content;
    }
}
